package com.woniuxy.student.controller;

import com.woniuxy.commons.entity.*;
import com.woniuxy.commons.service.RemotePaperService;
import com.woniuxy.student.sender.PluginSender;
import com.woniuxy.student.service.AnswerSheetService;
import com.woniuxy.student.service.TestPaperService;
import com.woniuxy.student.service.TestQuestionService;
import com.woniuxy.student.util.StudentCommonUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/17 0017-下午 3:57
 */
@RestController
@RequestMapping("/task")
public class TaskController {
    @Resource
    TestPaperService testPaperService;
    @Resource
    TestQuestionService testQuestionService;
    @Resource
    RemotePaperService remotePaperService;
    @Resource
    AnswerSheetService answerSheetService;
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PluginSender pluginSender;
    final static int stuno = 6;
    @GetMapping("/getPapers/{type}/{subject}/{page}")
    public ResponseEntity<PageBean<TestPaper>> getPapers(@PathVariable("type") String type, @PathVariable("subject") String subject, @PathVariable("page") Integer page){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            PageBean<TestPaper> pageBean = testPaperService.getPapersByCondition(stuno,type,subject,page);
            responseEntity.setData(pageBean);
            responseEntity.setCode(200);
        }catch (Exception e){
            System.out.println(e);
            responseEntity.setCode(2);
        }

        return responseEntity;
    }
    @GetMapping("/getDetailPaper/{paperid}")
    public ResponseEntity<TestPaper> getTestPaperById(@PathVariable("paperid") Integer paperid){
        ResponseEntity responseEntity = new ResponseEntity();
        try{
            TestPaper paper = testPaperService.getTestPaperById(paperid);
            List<TestQuestion> questions = testQuestionService.getAllQuestionByPaperId(paperid);
            System.out.println(questions);
            paper.setPaperQuestions(questions);
            responseEntity.setCode(200);
            responseEntity.setData(paper);
        }catch (Exception e){
            System.out.println(e);
            responseEntity.setCode(500);
        }
        return  responseEntity;

    }

    @GetMapping("/onlyRemotePaper/{paperid}")
    public ResponseEntity<TestPaper> onlyRemotePaper(@PathVariable("paperid") long paperid){
        ResponseEntity<TestPaper> responseEntity = new ResponseEntity<>();
        responseEntity.setCode(200);
        responseEntity.setData(remotePaperService.getPaperById(paperid));
        return responseEntity;
    }

    @GetMapping("/getRemotePaper/{paperid}/{first}")
    public ResponseEntity<TestPaper> getPaperById(@PathVariable("paperid") long paperid,@PathVariable("first") long first){
        ResponseEntity<TestPaper> responseEntity = new ResponseEntity<>();
        try{
            //先判断考试时间是否正确
            TestPaper simplePaper = testPaperService.getTestPaperById((int)paperid);
            if(StudentCommonUtil.canStartTest(simplePaper.getPaperDate(),simplePaper.getPaperDuration())==1){
                responseEntity.setCode(3);
                return responseEntity;
            }
            if(StudentCommonUtil.canStartTest(simplePaper.getPaperDate(),simplePaper.getPaperDuration())==2){
                responseEntity.setCode(4);
                return responseEntity;
            }
            TestPaper paper = remotePaperService.getPaperById(paperid);
            //如果是第一次，将考试的时间信息存储到redis
            if (first==1){
                redisTemplate.opsForValue().set("test:"+paperid, StudentCommonUtil.getTime(paper),Integer.parseInt(paper.getPaperDuration())+1, TimeUnit.MINUTES);
                String key = "answer:"+paperid+":"+stuno;
                redisTemplate.opsForValue().set(key,"");
                System.out.println("test:"+paperid+","+redisTemplate.opsForValue().get("test:"+paperid));
                long delayTime = StudentCommonUtil.getTime(paper)-new Date().getTime();
                pluginSender.send(key,(int)delayTime);
            }else{
                //不是就将从redis获取学生答案绑定
                paper = testPaperService.getStudentTestPaper(stuno,(int)paperid,paper);
            }
            responseEntity.setCode(200);
            responseEntity.setData(paper);
        }catch (Exception e){
            responseEntity.setCode(2);
        }
        return  responseEntity;
    }

    @GetMapping("/getRemoteHomework/{paperid}/{first}")
    public ResponseEntity<TestPaper> getHomeworkById(@PathVariable("paperid") long paperid,@PathVariable("first") long first) {
        ResponseEntity<TestPaper> responseEntity = new ResponseEntity<>();
        try{
            TestPaper paper = remotePaperService.getPaperById(paperid);
            if (first==1){
                //设置answer过期时间
                String key = "answer:"+paperid+":"+stuno;
                long expiretime = StudentCommonUtil.getHomeworkExpireTime(paper);
                redisTemplate.opsForValue().set(key,"",expiretime,TimeUnit.MILLISECONDS);
            }
            paper = testPaperService.getStudentTestPaper(stuno,(int)paperid,paper);
            responseEntity.setData(paper);
            responseEntity.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            responseEntity.setCode(2);
        }
        return responseEntity;
    }


    @PostMapping(value = "/submitHomework",produces = "application/json")
    public ResponseEntity<Void> submitHomework(@RequestParam Integer paperid,@RequestParam String nums) {
        ResponseEntity<Void> responseEntity = new ResponseEntity<>();
        String key = "answer:"+paperid+":"+stuno;
        int res = answerSheetService.insertAnswerSheet(key);
        responseEntity.setCode(200);
        return responseEntity;
    }


    @PostMapping(value = "/submitPaper",produces = "application/json")
    public ResponseEntity<Void> submitPaper(@RequestParam Integer paperid,@RequestParam String nums){
        ResponseEntity<Void> responseEntity = new ResponseEntity<>();
        //先将答案继续保存在redis
        String key = "answer:"+paperid+":"+stuno;
        //如果获取不到key或者获取的key为-1，则证明是超时提交
        Object code = redisTemplate.opsForValue().get(key);
        if(code==null||"-1".equals((String) code)){
            responseEntity.setCode(2);
            return responseEntity;
        }
        updateAnswer(paperid,nums);
        int res = answerSheetService.insertAnswerSheet(key);
        responseEntity.setCode(200);
        return  responseEntity;
    }

    @PostMapping(value = "/updateAnswer",produces = "application/json")
    public ResponseEntity<Void> updateAnswer(@RequestParam Integer paperid,@RequestParam String nums){
        ResponseEntity<Void> responseEntity = new ResponseEntity<>();
        int res = answerSheetService.updateAnswer(stuno,paperid,nums);
        responseEntity.setCode(200);
        return  responseEntity;
    }
    @GetMapping("/getRemain/{paperid}")
    public long getRemain(@PathVariable("paperid")Integer paperid){
        long expire = (long)redisTemplate.opsForValue().get("test:"+paperid);
        System.out.println("expire"+expire);
        long now = new Date().getTime();
        System.out.println("now"+now);
        return (expire-now)/1000/60;
    }

}
